import router from "@/router"

/**
 * 根据parentTarget找最顶层的路由
 * 
 * 直到某个路由不存在parentTarget
 */
export function findTopRoute(data: CustomRoute): CustomRoute {
  if (!data.meta.parentTarget) {
    return data
  } else {
    let parentRoute = router.getRoutes().filter(route => route.meta.target === data.meta.parentTarget)[0] as CustomRoute
    return parentRoute && findTopRoute(parentRoute)
  }
}

/**前往上一页，当没有历史路由时，前往首页 */
const routerBack = (redirect?: string) => {
  if (redirect) {
    router.push({
      path: redirect
    })
  } else {
    if (!window.history.state.back) {
      router.push('/')
    } else {
      router.back()
    }
  }
  location.reload()
}